import { useState } from 'react';
import { usePortfolio } from '../context/PortfolioContext';
import portfolioApi from '../utils/database';

const DataManager = () => {
  const { loadWorks, allWorks } = usePortfolio();
  const [isExporting, setIsExporting] = useState(false);
  const [isImporting, setIsImporting] = useState(false);

  // 导出数据
  const handleExport = async () => {
    try {
      setIsExporting(true);
      const data = {
        works: allWorks,
        exportDate: new Date().toISOString(),
        version: '1.0'
      };
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { 
        type: 'application/json' 
      });
      
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `portfolio-works-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (err) {
      console.error('导出失败:', err);
      alert('导出失败，请重试');
    } finally {
      setIsExporting(false);
    }
  };

  // 导入数据
  const handleImport = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
      setIsImporting(true);
      const text = await file.text();
      const data = JSON.parse(text);
      
      if (!data.works || !Array.isArray(data.works)) {
        throw new Error('无效的数据格式');
      }

      // 确认导入
      const confirmed = window.confirm(
        `确定要导入 ${data.works.length} 个作品吗？这将覆盖现有数据。`
      );
      
      if (!confirmed) return;

      // 使用后端的批量导入接口
      const worksToImport = data.works.map(work => {
        const { id, createdAt, updatedAt, ...workData } = work;
        return workData;
      });
      
      await portfolioApi.importWorks(worksToImport);

      // 重新加载数据
      await loadWorks();
      alert('数据导入成功！');
    } catch (err) {
      console.error('导入失败:', err);
      alert('导入失败：' + err.message);
    } finally {
      setIsImporting(false);
      event.target.value = ''; // 重置文件输入
    }
  };

  // 清空所有数据
  const handleClearAll = async () => {
    const confirmed = window.confirm(
      '确定要清空所有作品数据吗？此操作不可恢复！'
    );
    
    if (!confirmed) return;

    const doubleConfirmed = window.confirm(
      '请再次确认：这将永久删除所有作品数据！'
    );
    
    if (!doubleConfirmed) return;

    try {
      await portfolioApi.deleteAllWorks();
      await loadWorks();
      alert('所有数据已清空');
    } catch (err) {
      console.error('清空数据失败:', err);
      alert('清空数据失败，请重试');
    }
  };

  return (
    <div className="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm">
      <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">
        数据管理
      </h3>
      
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {/* 导出数据 */}
        <button
          onClick={handleExport}
          disabled={isExporting || allWorks.length === 0}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isExporting ? (
            <>
              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
              导出中...
            </>
          ) : (
            <>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
              导出数据
            </>
          )}
        </button>

        {/* 导入数据 */}
        <label className="flex items-center justify-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors cursor-pointer">
          {isImporting ? (
            <>
              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
              导入中...
            </>
          ) : (
            <>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
              </svg>
              导入数据
            </>
          )}
          <input
            type="file"
            accept=".json"
            onChange={handleImport}
            disabled={isImporting}
            className="hidden"
          />
        </label>

        {/* 清空数据 */}
        <button
          onClick={handleClearAll}
          disabled={allWorks.length === 0}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
          </svg>
          清空数据
        </button>
      </div>

      <div className="mt-4 text-sm text-gray-500 dark:text-gray-400">
        <p>• 导出：将所有作品数据保存为 JSON 文件</p>
        <p>• 导入：从 JSON 文件恢复作品数据（会覆盖现有数据）</p>
        <p>• 清空：删除所有作品数据（不可恢复）</p>
      </div>
    </div>
  );
};

export default DataManager;